import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
import vuexPer from "vuex-persistedstate";

export default new Vuex.Store({
  state: {
    username: "",
    shopcar: [],
    checked: false,
  },
  getters: {},
  mutations: {
    setUser(state, val) {
      state.username = val;
    },
    exit(state) {
      state.username = "";
    },
    add(state, val) {
      let flag = false;
      state.shopcar.forEach((i) => {
        if (i._id == val._id) {
          flag = true;
          i.num++;
        }
      });
      //如果商品存在就num++ 让flag变成true

      if (flag == false) {
        Vue.set(val, "num", 1);
        Vue.set(val, "status", false);
        //新添加字段的时候用set 是为了解决新添加的字段数据变了 视图不更新的问题
        // val.num=1
        // 设置的status代表是否选中
        state.shopcar.push(val);
      }
    },
    checkItem(state) {
      state.checked = state.shopcar.every((i) => i.status == true);
    },
    //上面的复选框控制下面的全选按钮
    checkAll(state) {
      state.shopcar.forEach((i) => {
        i.status = state.checked;
      });
    },
    //全选按钮控制上面复选框
  },
  actions: {},
  modules: {},
  plugins: [vuexPer()],
});
